<template>
	<view>
		<u-sticky bgColor="#fff">
			<u-tabs :list="tabs" @click="tabClick" :activeStyle="activeStyle" lineColor="#675f91" :current="current">
			</u-tabs>
			<u-line></u-line>
		</u-sticky>
		<template v-if="current == 0">
			<view class="bgw">
				<view class="flex wrapper">
					<view class="text-gray font-36">
						日期：
					</view>
					<view class="flex-1">
						<picker mode="date" :value="form.date" @change="bindDateChange">
							<view class="blank20"></view>
							<view class="flex">
								<view class="text-right flex-1  font-36 font-bold">
									{{form.date}}
								</view>
								<view class="ml5">
									<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
								</view>
							</view>
							<view class="blank20"></view>
						</picker>
					</view>
					<!-- <view class="btn-volume" @click="openRecorderPopup('date')">
					<u-icon name="mic" size="20"></u-icon>
				</view> -->
				</view>
				<u-line></u-line>
				<view class="flex wrapper">
					<view class="text-gray font-36">
						客户：
					</view>
					<view class="flex-1">
						<picker @change="bindCusChange" :value="cus_index" :range="cus_arr" range-key="label">
							<view class="blank20"></view>
							<view class="flex">
								<view class="text-right flex-1 font-36 font-bold">
									{{form.cus || '请选择'}}
								</view>
								<view class="ml5">
									<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
								</view>
							</view>
							<view class="blank20"></view>
						</picker>
					</view>
					<!-- <view class="btn-volume" @click="openRecorderPopup('cus')">
					<u-icon name="mic" size="20"></u-icon>
				</view> -->
				</view>
				<u-line></u-line>
				<view class="flex wrapper">
					<view class="text-gray font-36">
						餐别：
					</view>
					<view class="flex-1 flex" style="flex-wrap: wrap;padding: 10upx 0;">
						<view class="mr15" style="margin-top: 10upx;margin-bottom: 10upx;" v-for="(v, i) in dinner_type_arr"
							:key="i">
							<u-tag :text="v.label" :plain="dinner_type_index != i" type="primary" :name="i" size="large"
								@click="bindDinnerTypeChange(i)"></u-tag>
						</view>
					</view>
				</view>
				<u-line></u-line>
				<view class="flex wrapper">
					<view class="text-gray font-36">
						类别：
					</view>
					<view class="flex-1 flex" style="flex-wrap: wrap;padding: 10upx 0;">
						<view class="mr15" style="margin-top: 10upx;margin-bottom: 10upx;" v-for="(v, i) in sales_type_arr"
							:key="i">
							<u-tag :text="v.label" :plain="sales_type_index != i" type="primary" :name="i" size="large"
								@click="bindSalesTypeChange(i)"></u-tag>
						</view>
					</view>
				</view>
				<u-line></u-line>
				<view class="flex wrapper">
					<view class="text-gray font-36">
						餐标：
					</view>
					<view class="flex-1">
						<view class="blank20"></view>
						<input style="font-size: 36upx;text-align: left;" class="font-bold" v-model="form.price" type="digit"
							placeholder="请输入" />
						<view class="blank20"></view>
					</view>
					<recorder-btn @out="recorderBtnOutPrice"></recorder-btn>
					<!-- <view class="flex-1">
						<view class="blank20"></view>
						<view class="text-right text-red flex-1 font-36 font-bold">
							￥{{form_price}}
						</view>
						<view class="blank20"></view>
					</view> -->
				</view>
				<u-line></u-line>

				<view class="flex wrapper">
					<view class="text-gray font-36">
						份数：
					</view>
					<view class="flex-1">
						<view class="blank20"></view>
						<input style="font-size: 36upx;text-align: left;" class="font-bold" v-model="form.qty" type="number"
							placeholder="请输入" />
						<view class="blank20"></view>
					</view>
					<recorder-btn @out="recorderBtnOut"></recorder-btn>
				</view>
				<u-line></u-line>
				<view class="blank20"></view>
				<view class="wrapper">
					<view class="flex">
						<view class="flex-1">
							<u-button type="info" class="" text="重置" @click="resetForm"></u-button>
						</view>
						<view class="ml15"></view>
						<view class="flex-1">
							<u-button type="success" text="确定" @click="submitForm"></u-button>
						</view>
					</view>
				</view>
				<view class="blank20"></view>
			</view>
			<view class="blank20"></view>
			<view class="text-center font-bold font-36">
				历史录入内容
			</view>
			<view class="blank20"></view>
			<view class="wrapper">
				<template v-for="(v,i) in list">
					<view class="flex" v-if="v._is_new">
						<view class="bgw font-22 text-green" style="padding:10upx;">
							录入时间：{{v._time}}
						</view>
					</view>
					<view class="bgw" style="padding:0 10upx;">
						<view class="flex">
							<view class="col-item font-bold">
								{{v.date}}
							</view>
							<view class="flex-1 col-item font-bold">
								{{v.cus}}
							</view>
							<view class="flex-1 col-item font-bold">
								{{v.dinner}}
							</view>
							<view class="col-item">
								<u-icon name="trash" color="#999999" size="20" @click="del(i)"></u-icon>
							</view>
						</view>
						<u-line dashed></u-line>
						<view class="flex">
							<view class="flex-1 col-item">
								<text class="text-gray">份数：</text>
								<text class="font-bold text-green">{{v.qty}}</text>
							</view>
							<view class="flex-1 col-item">
								<text class="text-gray">餐标：</text>
								<text class="font-bold text-red">{{v.price}}</text>
							</view>
							<view class="flex-1 col-item">
								<text class="text-gray">总：</text>
								<text class="font-bold text-red">{{v.amount}}</text>
							</view>
						</view>
					</view>
					<view class="blank20"></view>
				</template>
			</view>
		</template>
		
		<!-- 异常录入 -->
		<template v-if="current == 1">
			<view class="bgw">
				<view class="flex wrapper">
					<view class="text-gray font-36">
						客户：
					</view>
					<view class="flex-1">
						<picker @change="bindComplainCusChange" :value="complain_cus_index" :range="complain_cus_arr" range-key="label">
							<view class="blank20"></view>
							<view class="flex">
								<view class="text-right flex-1 font-36 font-bold">
									{{complain_cus_arr[complain_cus_index].label}}
								</view>
								<view class="ml5">
									<u-icon name="arrow-down" color="#999999" size="20"></u-icon>
								</view>
							</view>
							<view class="blank20"></view>
						</picker>
					</view>
				</view>
				<u-line></u-line>
				<view class="flex wrapper">
					<view class="text-gray font-36">
						餐别：
					</view>
					<view class="flex-1 flex" style="flex-wrap: wrap;padding: 10upx 0;">
						<view class="mr15" style="margin-top: 10upx;margin-bottom: 10upx;" v-for="(v, i) in complain_dinner_arr"
							:key="i">
							<u-tag :text="v.label" :plain="complain_dinner_index != i" type="primary" :name="i" size="large"
								@click="bindComplainDinnerChange(i)"></u-tag>
						</view>
					</view>
				</view>
				<u-line></u-line>
				<view class="flex wrapper">
					<view class="text-gray font-36">
						问题：
					</view>
					<view class="flex-1">
						<view class="blank20"></view>
						<u-checkbox-group v-model="complain_category_value" placement="row" style="width: 100%;">
							<view class="flex" style="flex-wrap: wrap;">
								<template v-for="v in complain_category_arr">
									<view class="" style="margin: 15upx;">
										<u-checkbox size="24" labelSize="18" activeColor="#675f91" :label="v.label" :name="v.id"></u-checkbox>
									</view>
								</template>
							</view>
						</u-checkbox-group>
						<view class="blank20"></view>
					</view>
				</view>
				<u-line></u-line>
				<view class="blank20"></view>
				<view class="wrapper">
					<view class="flex">
						<view class="flex-1">
							<u-button type="info" class="" text="重置" @click="resetComplainForm"></u-button>
						</view>
						<view class="ml15"></view>
						<view class="flex-1">
							<u-button type="success" text="确定" @click="submitComplainForm"></u-button>
						</view>
					</view>
				</view>
				<view class="blank20"></view>
			</view>
			<view class="blank20"></view>
			<template v-if="false">
				<view class="text-center font-bold font-36">
						历史异常录入
					</view>
					<view class="blank20"></view>
					<view class="wrapper">
						<template v-for="(v,i) in 3">
							<view class="bgw" style="padding:0 10upx;">
								<view class="flex">
									<view class="flex-1 col-item font-bold">
										客户名称测试
									</view>
									<view class="flex-1 col-item font-bold">
										中餐
									</view>
									<view class="col-item">
										<u-icon name="trash" color="#999999" size="20"></u-icon>
									</view>
								</view>
								<u-line dashed></u-line>
								<view class="flex">
									<view class="text-gray col-item">问题：</view>
									<view class="flex-1 col-item font-bold text-red">
										菜品口味、菜品颜色、现场服务质量差
									</view>
								</view>
							</view>
							<view class="blank20"></view>
						</template>
					</view>
				
			</template>
		</template>

		<recorder-popup :open="recorderPopupOpen" @close="closeRecorderPopup" @add="addRecorderPopup"
			@check="recorderPopupCheck" :type="recorderPopupType"></recorder-popup>

	</view>
</template>

<script>
	import recorderBtn from "@/pagesA/components/recorder-btn/recorder-btn.vue";
	import recorderPopup from "./components/recorder-popup.vue";
	import {
		common_create,
		common_delete,
		common_write,
		user_input_detail_history,
		sales_cfg
	} from '@/common/api.js';
	export default {
		components: {
			recorderPopup,
			recorderBtn
		},
		data() {
			return {
				current: 0,
				activeStyle: {
					color: '#675f91'
				},
				tabs: [{
						name: '销售录入'
					},
					{
						name: '异常录入'
					},
				],
				cus_sales_cfg_obj: {},
				add_sales_record_id: this.make_add_function(),
				form: {
					date: '',
					cus: '',
					dinner_type: '',
					sales_type: '',
					qty: '',
					price:''
				},
				cus_index: 0,
				dinner_type_index: 0,
				sales_type_index: 0,
				role: null,
				userInfo: null,
				recorderPopupOpen: false,
				recorderPopupType: '',
				list: [],
				sales_cfg_data:{},
				cusObj:{},
				complain_category_arr:[],
				complain_dinner_arr:[],
				dinner_type_arr:[],
				complain_cus_index:0,
				complain_dinner_index:0,
				complain_category_value:[],
				model_name:''
			}
		},
		computed: {
			complain_cus_arr(){
				let write_cus_loc = this.$store.getters.get_role['报表模块']['销售'].write;
				let arr = write_cus_loc.map(v => {
					return {
						label: v[1],
						id: v[0]
					}
				})
				return arr
			},
			cus_arr() {	
				let write_cus_loc = this.$store.getters.get_role['报表模块']['销售'].write;
				let arr = write_cus_loc.map(v => {
					return {
						label: v[1],
						id: v[0]
					}
				})
				return arr
			},
			// dinner_type_arr() {
			// 	let dinner_type_category = this.$store.getters.get_dinner_type_category;
			// 	// console.log(dinner_type_category);
			// 	let arr = dinner_type_category.map(v => {
			// 		return {
			// 			label: v.name,
			// 			id: v.id,
			// 			dinner_type: v.dinner_type
			// 		}
			// 	})
			// 	return arr
			// },
			sales_type_arr() {
				let arr = [];
				try{
					// let sales_category_list = this.$store.getters.get_sales_category_list;
					let sales_category_list = this.sales_cfg_data.sales_category || [];
					// let cus_loc_id = this.cus_arr.find(v => v.label == this.form.cus).id;
					let cus_loc_id = this.cus_arr[this.cus_index].id;
					let cus_sales_category_ids = this.cusObj[cus_loc_id].cus_sales_category_ids;
					sales_category_list = sales_category_list.filter(v=>cus_sales_category_ids.includes(v.id));
					// let arr = [{id: 42,label:'快餐'},{id: 43,label:'特色'}];
					arr = sales_category_list.map(v => {
						return {
							label: v.name,
							id: v.id
						}
					})
				}catch(e){}	
				return arr
			},
			form_price() {
				try{
					let cus_loc_id = this.cus_arr[this.cus_index].id;
					let dinner_type_id = this.dinner_type_arr[this.dinner_type_index].id;
					let sales_category_id = this.sales_type_arr[this.sales_type_index].id;
					return this.get_price(cus_loc_id, dinner_type_id, sales_category_id, this.form.date);
				}catch(e){
					return 10;
				}
			}
		},
		methods: {
			change_form_price(){
				let price = 10;
				try{
					let cus_loc_id = this.cus_arr[this.cus_index].id;
					let dinner_type_id = this.dinner_type_arr[this.dinner_type_index].id;
					let sales_category_id = this.sales_type_arr[this.sales_type_index].id;
					price = this.get_price(cus_loc_id, dinner_type_id, sales_category_id, this.form.date);
				}catch(e){}
				this.form.price = price;
			},
			recorderBtnOut(d) {
				this.form.qty = Number(d);
			},
			recorderBtnOutPrice(d){
				this.form.price = Number(d);
			},
			tabClick(e) {
				this.current = e.index;
				// this.list = this.current == 0 ? this.list0 : this.list1;
			},
			get_price(cus_loc_id, dinner_type_id, sales_category_id, date) {
				let price = 10;
				try {
					let dayNum = new Date(date).getDay();
					let weekday = 'day';
					if (dayNum == 0) {
						weekday += '7'
					} else {
						weekday += (dayNum + 1)
					}
					price = this.cus_sales_cfg_obj[cus_loc_id][dinner_type_id][sales_category_id][weekday].sales_price;
				} catch (e) {
					//TODO handle the exception
				}
				return price
			},
			// recorderPopup 暂弃用
			recorderPopupCheck(data, result) {
				let _this = this;
				let {
					type,
					dinnerType,
					salesType,
					qty
				} = data;
				let dinnerTypeFlag = this.dinner_type_arr.find(v => v.label == dinnerType);
				let salesTypeFlag = this.sales_type_arr.find(v => v.label == salesType);
				result.dinnerTypeError = !dinnerTypeFlag;
				result.salesTypeError = !salesTypeFlag;
				if (dinnerTypeFlag && salesTypeFlag) {
					result.tips = [_this.form.date, '“', _this.form.cus, '”', dinnerType, salesType, qty, '份'].join('');
				}
			},
			openRecorderPopup(key) {
				console.log('openRecorderPopup');
				if (key != 'info') {
					uni.$u.toast('该功能暂未开启，请选择');
					return false;
				}
				this.recorderPopupOpen = true;
				this.recorderPopupType = key;
			},
			closeRecorderPopup() {
				this.recorderPopupOpen = false;
			},
			addRecorderPopup(data) {
				let _this = this;
				let {
					type,
					dinnerType,
					salesType,
					qty
				} = data;
				let item = {
					cus: _this.form.cus,
					date: _this.form.date,
					dinnerType: dinnerType,
					salesType: salesType,
					dinner: `${dinnerType}[${salesType}]`,
					qty: qty,
					// price:10,
					// amount:qty*10
				};
				this.addList(item);
			},
			submitForm() {
				let _this = this;
				_this.form.cus = this.cus_arr[this.cus_index].label
				_this.form.sales_type = this.sales_type_arr[this.sales_type_index].label;
				_this.form.dinner_type = this.dinner_type_arr[this.dinner_type_index].label;
				let item = {
					cus: _this.form.cus,
					date: _this.form.date,
					dinnerType: _this.form.dinner_type,
					salesType: _this.form.sales_type,
					dinner: `${_this.form.dinner_type}[${_this.form.sales_type}]`,
					qty: _this.form.qty,
					price:_this.form.price
				};
				this.addList(item);
			},
			addList(item) {
				if (!item.cus) {
					uni.$u.toast('客户错误');
					return;
				}
				if (!item.dinnerType) {
					uni.$u.toast('餐别错误');
					return;
				}
				if (!item.salesType) {
					uni.$u.toast('类别错误');
					return;
				}
				if (!item.price) {
					uni.$u.toast('餐标错误');
					return;
				}
				if (!item.qty) {
					uni.$u.toast('份数错误');
					return;
				}
				item.price = Number(item.price);
				item.qty = Number(item.qty);
				let flag = this.list.find(v => v.cus == item.cus && v.date == item.date && v.dinnerType == item.dinnerType && v
					.salesType == item.salesType);
				if (flag) {
					uni.$u.toast('数据已录入，如有修改请先删除‘历史录入内容’');
					return;
				}
				let cus_loc_id = this.cus_arr.find(v => v.label == item.cus).id;
				let dinner_type_id = this.dinner_type_arr.find(v => v.label == item.dinnerType).id;
				let sales_category_id = this.sales_type_arr.find(v => v.label == item.salesType).id;
				let sales_qty = item.qty;
				let date = item.date;
				// let price = this.get_price(cus_loc_id, dinner_type_id, sales_category_id, date);
				let price = item.price;
				let data = {
					id: this.add_sales_record_id(),
					date,
					cus_loc_id,
					dinner_type_id,
					sales_category_id,
					sales_qty,
					price,
					division_qty_json: false,
				};
				item.price = price;
				item.amount = price * sales_qty;

				// cus_loc_id: 4229
				// date: "2024-03-21"
				// dinner_type_id: 109
				// division_qty_json: {}
				// id: "virtual14"
				// price: 2
				// sales_amount: 0
				// sales_category_id: 42
				// sales_qty: 1			
				uni.showLoading({
					title: "加载中",
				});
				common_create({
					model_name: this.model_name,
					vals_list: [data]
				}).then((res) => {
					// id: 33008
					let newId = res.result[data.id].id;
					item.id = newId;
					let today = new Date();
					let _time = `${today.getHours()}` + `:` + `${today.getMinutes()}`.padStart(2, '0');
					item._time = _time;
					item._is_new = true;

					this.list.unshift(item);
				}).catch((res) => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			del(i) {
				let id = this.list[i].id;
				// let id = 33008;
				this.$store.dispatch('modal', '确认删除该内容？').then(() => {
					uni.showLoading({
						title: "加载中",
					});
					common_delete({
						model_name: this.model_name,
						ids: [id]
					}).then((res) => {
						this.list = this.list.filter((v, index) => i != index);
					}).catch(() => {

					}).finally(() => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
					})
				}).catch(() => {

				}).finally(() => {

				})
			},
			bindDateChange(e) {
				this.form.date = e.detail.value;
				this.change_form_price();
			},
			bindCusChange(e) {
				let index = e.detail.value;
				this.cus_index = index;
				this.form.cus = this.cus_arr[index].label;
				this.change_form_price();
			},
			bindDinnerTypeChange(index) {
				this.dinner_type_index = index;
				this.form.dinner_type = this.dinner_type_arr[index].label;
				this.change_form_price();
			},
			bindSalesTypeChange(index) {
				this.sales_type_index = index;
				this.form.sales_type = this.sales_type_arr[index].label;
				this.change_form_price();
			},
			bindComplainCusChange(e){
				let index = e.detail.value;
				this.complain_cus_index = index;
			},
			bindComplainDinnerChange(index){
				this.complain_dinner_index = index;
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				sales_cfg().then((res) => {
					let { cf_cus_complain_category,cus,dinner_type,sales_category } = res.result;
					this.sales_cfg_data = {
						cf_cus_complain_category,cus,dinner_type,sales_category
					};
					let cusObj = {};
					cus.forEach(v=>{
						let { cus_loc_id } = v;
						cusObj[cus_loc_id[0]] = v;
					});
					this.cusObj = cusObj;
					this.complain_category_arr = cf_cus_complain_category.map(v=>{
						return{
							label:v.name,
							id:v.id
						}
					});
					// console.log(this.complain_category_arr);
					let dinner_type_arr = dinner_type.map(v=>{
						return {
							id:v.id,
							label:v.name
						}
					});
					this.complain_dinner_arr = dinner_type_arr;
					this.dinner_type_arr = dinner_type_arr
					this.resetForm();
					this.resetComplainForm();
				}).catch(() => {
					
				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
				user_input_detail_history().then((res) => {
					let {
						sales_data,
						model_name
					} = res.result;
					let list = [];
					sales_data.forEach(v => {
						let item = {
							...v,
							cus: v.cus_loc_id[1],
							dinnerType: v.dinner_type_id[1],
							salesType: v.sales_category_id[1],
							date: v.date,
							qty: v.sales_qty,
							price: v.price,
							amount: v.sales_amount
						};
						item.dinner = `${item.dinnerType}[${item.salesType}]`;
						list.push(item);
					})
					this.list = list;
					this.model_name = model_name;

				}).catch(() => {

				}).finally(() => {
					// this.loadingStatus = 'end';
				})
			},
			submitComplainForm(){
				uni.$u.toast('功能开发中，请期待...');
			},
			resetComplainForm(){
				let default_dinner_type_index = this.complain_dinner_arr.findIndex(v => v.label == '中餐');
				if (default_dinner_type_index == -1) {
					default_dinner_type_index = 0;
				}
				this.complain_dinner_index = default_dinner_type_index;
				
				this.complain_cus_index = 0;
				this.complain_category_value = [];
			},
			resetForm() {
				// console.log(this.dinner_type_arr);
				this.form.date = this.today_year_month_day;
				this.form.cus = this.cus_arr[0].label;
				this.form.sales_type = this.sales_type_arr[0].label;
				this.form.qty = 0;
				this.cus_index = 0;
				this.sales_type_index = 0;
				let default_dinner_type_index = this.dinner_type_arr.findIndex(v => v.label == '中餐');
				if (default_dinner_type_index == -1) {
					default_dinner_type_index = 0;
				}
				this.dinner_type_index = default_dinner_type_index;
				this.form.dinner_type = this.dinner_type_arr[default_dinner_type_index].label;
				this.change_form_price();
			},
			set_cus_sales_cfg_obj() {
				let cus_sales_cfg = this.$store.getters.get_cus_sales_cfg;
				let cus_sales_cfg_obj = {};
				cus_sales_cfg.forEach(v => {
					let {
						cus_loc_id,
						dinner_type_id,
						sales_category_id,
						weekday
					} = v;
					!cus_sales_cfg_obj[cus_loc_id] && (cus_sales_cfg_obj[cus_loc_id] = {});
					!cus_sales_cfg_obj[cus_loc_id][dinner_type_id] && (cus_sales_cfg_obj[cus_loc_id][dinner_type_id] = {});
					!cus_sales_cfg_obj[cus_loc_id][dinner_type_id][sales_category_id] && (cus_sales_cfg_obj[cus_loc_id][
						dinner_type_id
					][sales_category_id] = {});
					cus_sales_cfg_obj[cus_loc_id][dinner_type_id][sales_category_id][weekday] = v;
				});
				this.cus_sales_cfg_obj = cus_sales_cfg_obj;
				// console.log(this.cus_sales_cfg_obj);
			},
		},
		onShow() {
			this.set_cus_sales_cfg_obj();
			try {
				this.role = this.$store.getters.get_role;
				this.userInfo = this.$store.getters.get_userInfo;
			} catch (e) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		},
		onLoad(d) {
			this.getData();
		}
	}
</script>

<style>
	.btn-volume {
		padding: 30upx 30upx;
	}

	.col-item {
		padding: 20upx 10upx;
		/* text-align: center; */
	}
</style>